﻿using System;
using System.Net;

namespace VASJ.Model.Helper
{
    public class IPAddressHelper
    {
        public static string LocalComputerName = Dns.GetHostName();

        public static string HostName = Dns.GetHostName();

        /// <summary>
        /// Gets the computer's external IP address from the internet.
        /// </summary>
        /// <returns></returns>
        public static IPAddress GetExternalAddress()
        {
            //
            //<html><head><title>Current IP Check</title></head><body>Current IP Address: 129.98.193.226</body></html>
            //
            var html = new WebClient().DownloadString("http://checkip.dyndns.com/");
            var ipStart = html.IndexOf(": ", StringComparison.OrdinalIgnoreCase) + 2;
            return IPAddress.Parse(html.Substring(ipStart, html.IndexOf("</", ipStart, StringComparison.OrdinalIgnoreCase) - ipStart));
        }

        public static IPAddress[] GetLocalIPAddressList()
        {
            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            return localIPs;
        }

        public static IPAddress[] GetHostIPAddressList(string host)
        {
            IPAddress[] localIPs = Dns.GetHostAddresses(host);
            return localIPs;
        }

        //
        //IsLocalIpAddress("localhost");        // true (loopback name)
        //IsLocalIpAddress("127.0.0.1");        // true (loopback IP)
        //IsLocalIpAddress("MyNotebook");       // true (my computer name)
        //IsLocalIpAddress("192.168.0.1");      // true (my IP)
        //IsLocalIpAddress("NonExistingName");  // false (non existing computer name)
        //IsLocalIpAddress("99.0.0.1");         // false (non existing IP in my net)
        //
        public static bool IsLocalIpAddress(string host)
        {
            try
            {
                // get host IP addresses
                IPAddress[] hostIPs = Dns.GetHostAddresses(host);

                // get local IP addresses
                IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

                // test if any host IP equals to any local IP or to localhost
                foreach (IPAddress hostIP in hostIPs)
                {
                    // is localhost
                    if (IPAddress.IsLoopback(hostIP)) return true;

                    // is local address
                    foreach (IPAddress localIP in localIPs)
                    {
                        if (hostIP.Equals(localIP)) return true;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log.Error(ex);
            }
            return false;
        }
    }
}
